<template>
  <el-container class="main_con">
    <ufrom @submit="saveData" ref="ufrom">


      <el-form ref="formRules" :model="myform" label-width="120px" class="form_box" :rules="formRules">
        <div class="setting_body_item">
          <div class="header">基本信息</div>
          <div class="conetnt edit_con">
            <div class="edit_content">
              <el-form-item label="活动名称" prop="title"><el-input :disabled="isEdit" v-model="myform.title" size="small" style="width:350px"></el-input></el-form-item>
              <el-form-item label="活动期限" prop="times" v-if="!isEdit">
                <el-date-picker
                  size="small"
                  style="width:350px"
                  v-model="myform.times"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd HH:mm"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="活动期限" v-else>
                <el-date-picker size="small" disabled v-model="myform.start_time" type="datetime" placeholder="开始日期" value-format="yyyy-MM-dd HH:mm"></el-date-picker>
                <span style="margin: 0 10px;">至</span>
                <el-date-picker size="small" v-model="myform.end_time" type="datetime" placeholder="结束日期" value-format="yyyy-MM-dd HH:mm"></el-date-picker>
              </el-form-item>
              <el-form-item label="活动渠道" prop="client_type">
                <el-checkbox-group v-model="myform.client_type" :disabled="isEdit">
                  <el-checkbox v-entry="1" :label="'1'">微信小程序</el-checkbox>
                  <el-checkbox v-entry="2" :label="'2'">微信公众号</el-checkbox>
                  <el-checkbox v-entry="3" :label="'3'">H5</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </div>
        </div>
        <div class="setting_body_item">
          <div class="header">规则设置</div>
          <div class="conetnt edit_con">
            <div class="edit_content">
              <el-form-item label="商品">
                <div class="box">
                  <el-button :disabled="isEdit" type="primary" size="small" @click="showSelect">添加商品</el-button>
                  <el-table class="mt_15" :data="myform.Prolist" :span-method="arraySpanMethod">
                    <el-table-column width="250" label="商品" prop="name">
                      <template slot-scope="scope">
                        <div class="u-flex">
                          <vimage style="width: 60px; height: 60px;margin-right:10px;" :src="scope.row.master"></vimage>
                          <span style="flex: 1;">{{ scope.row.name }}</span>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="sell_price" label="售价"></el-table-column>
                    <el-table-column prop="total" label="库存">
                      <template slot-scope="scope">
                        <!-- {{ scope.row.total}} -->
                        {{ scope.row.total - scope.row.sell }}
                      </template>
                    </el-table-column>

                    <el-table-column prop="" label="预售库存">
                      <template slot-scope="scope">
                        <template v-if="scope.row.has_sku">
                          <el-button
                            type="success"
                            v-if="scope.row.sku && scope.row.sku.length > 0"
                            style="width:100%"
                            size="mini"
                            @click="selectsku(scope.row, scope.$index)"
                            plain
                          >
                            修改
                          </el-button>
                          <el-button
                            type="danger"
                            v-else="scope.row.sku && scope.row.sku.length > 0"
                            style="width:100%"
                            size="mini"
                            @click="selectsku(scope.row, scope.$index)"
                            plain
                          >
                            设置
                          </el-button>
                        </template>
                        <el-form-item v-else style="margin:20px 0;" :prop="'Prolist.' + scope.$index + '.activity_stock'" :rules="formRules.activity_stock">
                          <el-input :disabled="isEdit" size="mini" v-model="scope.row.activity_stock"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="" label="预售价格">
                      <template slot-scope="scope">
                        <el-form-item style="margin:20px 0;" :prop="'Prolist.' + scope.$index + '.activity_price'" :rules="formRules.activity_price">
                          <el-input :disabled="isEdit" size="mini" v-model="scope.row.activity_price"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template slot-scope="scope">
                        <el-button v-if="!isEdit" type="text" @click="deleteData(scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-form-item>

              <el-form-item label="分销">
                <el-radio-group :disabled="isEdit" v-model="myform.use_agent">
                  <el-radio :label="1">开启</el-radio>
                  <el-radio :label="0">关闭</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="限购次数">
                <el-radio-group :disabled="isEdit" v-model="myform.is_limit_type">
                  <div class="u-flex" style="margin-top:10px"><el-radio :label="0">不限制</el-radio></div>
                  <div class="tips"><span></span></div>
                  <div class="u-flex">
                    <el-radio :label="1">活动期内每人最多购买</el-radio>
                    <el-input :disabled="isEdit" size="mini" style="width:150px" v-model="myform.limit_type_one">
                      <template slot="append">
                        件
                      </template>
                    </el-input>
                  </div>
                  <div class="tips"><span>若开启，活动期间内每人每件商品最多支持购买数量，如商品A活动期间最多支持购买200件</span></div>
                  <div class="u-flex">
                    <el-radio :label="2">活动期内每人每天最多购买</el-radio>
                    <el-input :disabled="isEdit" size="mini" style="width:150px" v-model="myform.limit_type_two">
                      <template slot="append">
                        件
                      </template>
                    </el-input>
                  </div>
                  <div class="tips"><span>若开启，活动期间内每人每天针对单个商品最多购买数量，如每人每天最多购买商品A200件</span></div>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="预计发货时间">
                <el-radio-group :disabled="isEdit" v-model="myform.send_at_type">
                  <el-radio :label="1">特定时间</el-radio>
                  <el-radio :label="2">付款成功</el-radio>
                </el-radio-group>
                <div class="box">
                  <el-form-item v-if="myform.send_at_type == 1" prop="send_at_time">
                    <div class="u-flex">
                      <el-date-picker
                        :disabled="isEdit"
                        size="small"
                        v-model="myform.send_at_time"
                        type="datetime"
                        placeholder="发货时间"
                        value-format="yyyy-MM-dd HH:mm"
                      ></el-date-picker>
                      <span class="u-m-l-10">开始发货</span>
                    </div>
                  </el-form-item>
                  <el-form-item v-if="myform.send_at_type == 2" prop="send_at_day">
                    <div class="u-flex">
                      <el-input :disabled="isEdit" size="mini" style="width:150px" v-model="myform.send_at_day">
                        <template slot="append">
                          天
                        </template>
                      </el-input>
                      <span class="u-m-l-10">后开始发货</span>
                    </div>
                  </el-form-item>
                </div>
              </el-form-item>
              <el-form-item label="未支付取消时间">
                <el-radio-group :disabled="isEdit" v-model="myform.cancel_type">
                  <el-radio :label="0">系统默认</el-radio>
                  <el-radio :label="1">自定义</el-radio>
                </el-radio-group>
                <div class="box" v-if="myform.cancel_type == 1">
                  <el-form-item prop="cancel_time">
                    <div class="u-flex">
                      <el-input :disabled="isEdit" size="mini" style="width:150px" v-model.number="myform.cancel_time">
                        <template slot="append">
                          分钟
                        </template>
                      </el-input>
                    </div>
                    <div style="color:#909399;font-size:12px;">订单取消时间必须在20-1440分钟之间</div>
                  </el-form-item>
                </div>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </ufrom>

    <el-dialog title="选择商品" :visible.sync="showSelectPro" width="50%" append-to-body>
      <SelectProduct :active_type="1" ref="selectproduct" :data="selectPro" :is_nIg="true" :limit="10" @outData="closePro"></SelectProduct>
    </el-dialog>
    <el-dialog title="价格设置" :visible.sync="showSelectSku" width="70%" append-to-body><selectsku :isEdit="isEdit" ref="selectsku" @outData="getskuData"></selectsku></el-dialog>
  </el-container>
</template>

<script>
import {addpresell, getpresell, editpresell} from '@/api/mall/presell';
import {getPro} from '@/api/shop/product';
import SelectProduct from '@/components/SelectProduct/index';
import selectsku from './components/selectsku.vue';

import {jur_addons_item, jur_addons} from '@/utils/jurisdiction';
export default {
  data() {
    var checkstock = (rule, value, callback) => {
      console.log(rule);
      let a = rule.field;
      let c = a.replace(/Prolist./g, '');
      let d = c.split('.');
      let id = Number(d[0]);
      value = Number(value);
      if (!value) {
        return callback(new Error('不能为空'));
      }
      setTimeout(() => {
        let stock = this.myform.Prolist[id].total - this.myform.Prolist[id].sell;
        if (stock < value) {
          callback(new Error('活动库存不能大于实际库存'));
        } else {
          callback();
        }
      }, 1000);
    };
    var checkprice = (rule, value, callback) => {
      console.log(rule);
      let a = rule.field;
      let c = a.replace(/Prolist./g, '');
      let d = c.split('.');
      let id = Number(d[0]);
      value = Number(value);
      if (!value) {
        return callback(new Error('不能为空'));
      }
      setTimeout(() => {
        let sell_price = this.myform.Prolist[id].sell_price;
        if (sell_price < value) {
          callback(new Error('活动价格不能大于售卖价格'));
        } else {
          callback();
        }
      }, 1000);
    };
    return {
      rk: 0,
      prize_index: '0',
      prize_time: '',
      id: '',

      source: [],
      selectPro: [],
      myform: {
        title: '', //,	必填	string	名字
        start_time: '', //,	必填	date	开始时间
        end_time: '', //,	必填	date	结束时间
        client_type: [], //,	多选	string	来源（逗号分隔）1微信公众号2小程序3h5
        use_agent: 0, //,	必填	int	0分销
        is_limit_type: 0,
        limit_type_one: 0, //,必填	string	{0,0,0}限购次数 {选项，活动期内每人最多购买, 活动期内每人每天最多购买}
        limit_type_two: 0,
        is_show: 0,
        is_show_time: '', //,
        times: [],
        Prolist: [],
        send_at_type: 1,
        send_at_time: '',
        send_at_day: '',
        cancel_type: 0,
        cancel_time: ''
      },
      form: {
        title: '', //,	必填	string	名字
        start_time: '', //,	必填	date	开始时间
        end_time: '', //,	必填	date	结束时间
        client_type: '', //,	多选	string	来源（逗号分隔）1微信公众号2小程序3h5
        rules: {
          use_agent: 0, //,	必填	int	0分销
          limit_type: [0, 0, 0], //,必填	string	{0,0,0}限购次数 {选项，活动期内每人最多购买, 活动期内每人每天最多购买}
          is_show: 0 //,
        } //,	必填	string	规则设置
      },
      formRules: {
        title: [
          {
            required: true,
            message: '请输入活动名称',
            trigger: 'blur'
          }
        ],
        times: [
          {
            required: true,
            message: '请至少选择一个活动渠道',
            trigger: 'change'
          }
        ],
        client_type: [
          {
            required: true,
            message: '请至少选择一个活动渠道',
            trigger: 'change'
          }
        ],

        is_show_time: [
          {
            required: true,
            message: '请选择预热时间',
            trigger: 'blur'
          }
        ],
        activity_stock: [
          {
            validator: checkstock,
            trigger: ['blur', 'change']
          }
        ],
        activity_price: [
          {
            validator: checkprice,
            trigger: ['blur', 'change']
          }
        ],
        cancel_time: [
          {
            required: true,
            message: '订单取消时间必须在20-1440分钟之间'
          },
          {type: 'number', min: 20, max: 1440, message: '订单取消时间必须在20-1440分钟之间', trigger: 'blur'}
        ],
        send_at_time: [
          {
            required: true,
            message: '请选择发货时间',
            trigger: 'blur'
          }
        ],
        send_at_day: [
          {
            required: true,
            message: '请输入发货时间',
            trigger: 'blur'
          }
        ]
      },
      showSelectPro: false,
      showSelectSku: false,
      isEdit: false
    };
  },
  created() {
    if (this.$route.query.id) {
      //编辑状态
      this.isEdit = true;
      this.id = this.$route.query.id;
      this.getdetail();
    }
  },

  components: {
    SelectProduct,
    selectsku
  },
  methods: {
    getdetail() {
      let data = {
        id: this.id
      };
      getpresell(data).then(res => {
        let json = res.msg;
        this.myform.title = json.title;
        this.myform.client_type = json.client_type.split(',');
        this.myform.start_time = json.start_time;
        this.myform.end_time = json.end_time;
        let rules = JSON.parse(json.rules);
        this.myform.limit_time = rules.limit_time;
        this.myform.use_agent = rules.use_agent;

        this.myform.is_limit_type = rules.limit_type[0];
        this.myform.limit_type_one = rules.limit_type[1];
        this.myform.limit_type_two = rules.limit_type[2];
        this.myform.send_at_type = rules.send_at[0];
        this.myform.send_at_time = rules.send_at[1];
        this.myform.send_at_day = rules.send_at[2];
        this.myform.cancel_type = rules.cancel_time==0?0:1

        if(rules.cancel_time!=0){
            this.myform.cancel_time=rules.cancel_time
        }

        let commodity = json.commodity;
        commodity.forEach(c => {
          c.name = c.goods.name;
          c.master = c.goods.master;
          c.total = c.goods.total;
          c.sell = c.goods.sell;
          c.sell_price = c.goods.sell_price;
        });
        this.myform.Prolist = commodity;
      });
    },
    deleteData(i) {
      this.myform.Prolist.splice(i, 1);
      this.selectPro.splice(i, 1);
      console.log(this.selectPro);
    },

    selectsku(item, index) {
      this.showSelectSku = true;
      this.$nextTick(() => {
        let data = {
          id: item.id,
          index: index
        };
        if (this.isEdit) {
          data.id = item.commodity_id;
        }

        if (item.sku) {
          data.sku = item.sku;
        }
        if (this.myform.type == 2) {
          data.laddernum = this.myform.laddernum;
          this.$refs.selectsku.getskulist(data);
        } else {
          this.$refs.selectsku.getskulist(data);
        }
      });
    },

    //选择商品
    showSelect() {
      // this.rk++;
      this.showSelectPro = true;
      this.$nextTick(() => {
        this.$refs.selectproduct.initdata();
      });
    },
    editsave() {
      let data = {
        is_show: [this.myform.is_show, this.myform.is_show_time],
        end_time: this.myform.end_time,
        id: this.id
      };
      editpresell(data).then(res => {
        this.$router.push({
          path: '/presell/list'
        });
      }).catch(e => {
        this.$refs.ufrom.init()
      });
    },
    saveData() {
      let _this = this;
      this.$refs['formRules'].validate(valid => {
        if (valid) {
          if (this.id) {
            _this.editsave();
          } else {
            _this.save();
          }
        } else {
          this.$refs.ufrom.init();
        }
      });
    },
    save() {
      let rules = {
        use_agent: this.myform.use_agent,
        send_at: [this.myform.send_at_type, this.myform.send_at_time, this.myform.send_at_day],
        limit_type: [this.myform.is_limit_type, this.myform.limit_type_one, this.myform.limit_type_two],
        cancel_time: this.myform.cancel_type == 0 ? 0 : this.myform.cancel_time
      };

      let commodity = [];
      this.myform.Prolist.forEach(a => {
        if (a.has_sku) {
          let sku = JSON.parse(JSON.stringify(a.sku));
          commodity.push({
            commodity_id: a.id,
            has_sku: a.has_sku,
            activity_stock: 0,
            activity_price: 0,
            skus: sku
          });
        } else {
          let activity_price = a.activity_price;
          commodity.push({
            commodity_id: a.id,
            activity_stock: a.activity_stock,
            activity_price: activity_price,
            leader_price: a.leader_price || -1,
            has_sku: a.has_sku
          });
        }
      });

      let obj = {
        title: this.myform.title,
        start_time: this.myform.times[0],
        end_time: this.myform.times[1],
        type: this.myform.type,
        client_type: this.myform.client_type.join(','),
        rules: rules,
        commodity: commodity
      };
      addpresell(obj).then(res => {
        // this.$message.success('创建成功');
        this.$router.push({
          path: '/presell/list'
        });
      }).catch(e => {
        this.$refs.ufrom.init()
      });
    },
    arraySpanMethod({row, column, rowIndex, columnIndex}) {
      if (row.has_sku) {
        let num = 2;
        let end = 5;
        if (columnIndex == 3) {
          let num = 2;
          return [1, num];
        } else if (columnIndex > 3 && columnIndex < end) {
          return [0, 0];
        } else {
          return [1, 1];
        }
      }
    },
    //关闭选择产品框
    closePro(Prolist) {
      if (Prolist) {
        this.selectPro = JSON.parse(JSON.stringify(Prolist));
        Prolist.forEach(a => {
          let b = {};
          if (a.has_sku) {
            b.sku = [];
          } else {
            b.activity_stock = '';
            b.activity_price = '';
          }
          const c = Object.assign(b, a);
          if (this.myform.Prolist.findIndex(_ => _.id == c.id) == -1) {
            this.myform.Prolist.push(c);
          }
        });
        // this.Prolist = Prolist;
      }

      this.showSelectPro = false;
    },
    getskuData(list, i) {
      this.showSelectSku = false;
      if (list) {
        this.myform.Prolist[i].sku = list;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.tips {
  color: #939799;
  margin: 10px 0;
  font-size: 12px;
}
</style>
